package com.jn.personal;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jn.common.base.BaseFragment;
import com.jn.common.database.DBHelper;
import com.jn.common.event.LoginEvent;
import com.jn.common.event.UserEvent;
import com.jn.common.service.ILoginService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

@Route(path = "/personal/PersonalFragment")
public class PersonalFragment extends BaseFragment implements View.OnClickListener {

   private TextView mUserNameView;
   private Button mLogoutButton;
   private Button mMyFinancingButton;
   private String userName;
   private DBHelper mDbHelper;
   @Override
   protected int getLayoutId() {
      return R.layout.fragment_personal;
   }

   @Override
   protected void init() {
      mUserNameView = mView.findViewById(R.id.user_name_view);
      mLogoutButton = mView.findViewById(R.id.logout_button);
      mMyFinancingButton = mView.findViewById(R.id.my_financing);
      mLogoutButton.setOnClickListener(this);
      mMyFinancingButton.setOnClickListener(this);
      EventBus.getDefault().register(this);
      mDbHelper = DBHelper.getInstance(getContext());
      mUserNameView.setText(mDbHelper.getLoginUser());
   }

   @Subscribe(threadMode = ThreadMode.MAIN)
   public void onUserEvent(UserEvent event) {
      userName = event.getUserName();
      Log.d("asdf", "----onLoginEvent == " + userName);
      mUserNameView.setText(userName);
   }

   @Override
   protected void onFragmentChanged() {
      mUserNameView.setText(mDbHelper.getLoginUser());
   }

   @Override
   public void onClick(View v) {
      int id = v.getId();
      if (id == R.id.logout_button) {
         ILoginService loginService = (ILoginService) ARouter.getInstance()
                 .build("/login/service")
                 .navigation();
         if (loginService != null) {
            loginService.setLogin(false);
            //EventBus.getDefault().post(new LoginEvent(false));
         }
         DBHelper dbHelper = DBHelper.getInstance(getContext());
         dbHelper.updateLoginState(dbHelper.getLoginUser(), false);
      } else if (id == R.id.my_financing) {
         Intent intent = new Intent(getContext(), PersonalActivity.class);
         startActivity(intent);
      }
   }

   @Override
   public void onDestroy() {
      super.onDestroy();
      EventBus.getDefault().unregister(this);
   }
}
